package cn.ly.core.concurrent;

import java.util.concurrent.*;

public class CompletionServiceTest implements Callable<String>{
	
	private int id;
	
	public CompletionServiceTest(int i){
		this.id = i;
	}
	
	@Override
	public String call() throws Exception {
		int time = (int)(Math.random()*10000);
		try{
			System.out.println("[" + id + "] start ...");
			Thread.sleep(time);
			System.out.println("[" + id + "] end");
		}catch(Exception e){
			e.printStackTrace();
		}
		return "执行结果[" + id + "]:" + time;
	}
	
	public static void main(String[] args) throws Exception{
		ExecutorService service = Executors.newCachedThreadPool();
		CompletionService<String> cs = new ExecutorCompletionService<String>(service);
		for(int i=0; i<10; i++){
			cs.submit(new CompletionServiceTest(i));//执行任务
		}
		Thread t = new Thread(){
			public void run(){
				for(int i=0; i<10; i++){     //CompletionService 可以用来管理异步 IO
					try {                    //得到每个任务的返回结果
						Future f = cs.take();//执行任务的结果保存在Future中，Future.get()可以获得返回结果。
						System.out.println(f.get());
					} catch (InterruptedException | ExecutionException e) {
						e.printStackTrace();
					}
				}
			}
		};
		t.start();
		service.shutdown();
	}

}
